package android.bbs;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bbs.notice.NoticeConst;
import android.bbs.notice.NoticeDTO;
import android.bbs.notice.Notice_create;
import android.bbs.notice.Notice_read;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.utility.Utility;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.piano_application.R;
/**
 * 공지사항
 * */
public class Tab1 extends Activity implements OnClickListener{
	
	ArrayList<NoticeDTO> noticelist;
	ProcessGet processGet;
	
	private ImageView img_create;
	private int cnt = 0;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bbs_notice);
    	
        img_create = (ImageView)findViewById(R.id.img_create);
        img_create.setOnClickListener(this);
        
    	noticeList();
        
	}
	
	public void noticeList(){
		StringBuilder html = new StringBuilder();
        try {
            BufferedReader br = Utility.loadHTML(NoticeConst.LIST);
       
       
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                
                br.close();

                Tab1.this.noticelist = new  ArrayList<NoticeDTO>(); // 출력 문자열 
              
                JSONObject noticeobj = new JSONObject(html.toString());
                JSONArray noticeja = noticeobj.getJSONArray("data");
                
                
                for (int i = 0; i < noticeja.length(); i++) {
                      
                    JSONObject item = noticeja.getJSONObject(i);
                    NoticeDTO noticedto = new NoticeDTO();
                    noticedto.setNoticeno(item.getInt("noticeno"));
                    noticedto.setNickname(item.getString("nickname"));
                    noticedto.setTitle(item.getString("title"));
                    noticedto.setContents(item.getString("contents"));
                    noticedto.setProfilephoto(item.getString("profilephoto"));
                    noticedto.setNoticedate(item.getString("noticedate").substring(5, 10));
                    
                    if(i == noticeja.length()-1){
                    	cnt = item.getInt("noticeno");
                    }
                    
                    Tab1.this.noticelist.add(noticedto);
                }   
                setAdapter(Tab1.this.noticelist);
                Log.d("D", "Adapter use");
             } catch (Exception e) {
                 Log.d("D", e.toString());
            }
	}
	
	public void setAdapter(final ArrayList<NoticeDTO> noticelist){
        ListAdapter noticeAdapter = new ListAdapter(Tab1.this, R.layout.notice_row, noticelist);
        ListView notice_list = (ListView)findViewById(R.id.isv_notice);
        notice_list.setAdapter(noticeAdapter);
        notice_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int noticeno = noticelist.get(position).getNoticeno();

                Intent intent = null;
    			intent = new Intent(getApplicationContext(), Notice_read.class);
    			intent.putExtra("noticeno", noticeno);
    			startActivity(intent);
    			finish();
            }
        });                 
    }

    //어댑터 클래스
    class ListAdapter extends BaseAdapter {
        Context maincon;
        LayoutInflater Inflater;
        ArrayList<NoticeDTO> noticelist;
        int layout;
        
        public ListAdapter(Context context, int layout, ArrayList<NoticeDTO> noticelist) {
            maincon = context;
            Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.layout = layout;
            this.noticelist = noticelist;

        }

        public int getCount() {
           return noticelist.size();
        }

        public NoticeDTO getItem(int position) {
            return (NoticeDTO)noticelist.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        // 각 항목의 뷰 생성
        public View getView(int position, View convertView, ViewGroup parent) {
             if (convertView == null) {
                convertView = Inflater.inflate(layout, parent, false);
            }
           
            TextView txv_title = (TextView)convertView.findViewById(R.id.txv_title);
            txv_title.setText(noticelist.get(position).getTitle());

            TextView txv_name = (TextView)convertView.findViewById(R.id.txv_name);
            txv_name.setText(noticelist.get(position).getNickname());
            
            TextView txv_date = (TextView)convertView.findViewById(R.id.txv_date);
            txv_date.setText(noticelist.get(position).getNoticedate());
            
            return convertView;
        }
    }
	
    
    class ProcessGet extends Thread{
        String _addr;

        ProcessGet(String addr) {
            _addr = addr;
        }

        public void run() {

            HttpGet get = new HttpGet(_addr);
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                client.execute(get, responseHandler);
            } 
            catch (Exception e) {;}
        }        
    }
    
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) {
 
            StringBuilder html = new StringBuilder(); 
            String message = "";
            try {                
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                br.close();

                JSONObject obj = new JSONObject(html.toString());
                
                String code = obj.getString("code");
                message = obj.getString("message");
                
                if (code.equals("success")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if (code.equals("fail")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 2;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if ( code.equals("error")){
                	Message msg = msgHandler.obtainMessage();
                    msg.what = 3;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                }
            } catch (Exception e) {
                Message msg = msgHandler.obtainMessage();
                msg.what = 4;
                msg.obj = message;
                msgHandler.sendMessage(msg);
            }
            return html.toString();
        }
    };
	
    @SuppressLint("HandlerLeak")
	Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("D", "handleMessage Call");
            // Log.d("D", "msg.what: " + msg.what);
            
            if (msg.what == 1){
                setResult(RESULT_OK, (new Intent()).setAction("SUCCESS")); // "SUCCESS"를 넘겨준다.
                // 종료 
                noticeList();
            }else if (msg.what == 2){
                
            }else if (msg.what == 3){
                
            }else if (msg.what == 4){
            }            
        }
    };
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.img_create) {
			Intent intent = null;
			intent = new Intent(getApplicationContext(), Notice_create.class);
			intent.putExtra("noticeno", cnt);
			startActivity(intent);
			finish();
        } 
	}
	
	 public boolean onCreateOptionsMenu(Menu menu) {
	        super.onCreateOptionsMenu(menu);
	        menu.add(0, 1, 0, "새로 고침");
	        return true;
	    }

	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case 1:
	        	noticeList();
	            return true;
	        }

	        return false;
	    }
	
		
}
